﻿CREATE PROCEDURE [Event].[RegisterAttendance]
	@EventID INT,
	@AccountID INT
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;

DECLARE @AttendeeCount AS INT = 0;

BEGIN TRY
  BEGIN TRANSACTION
  
  SELECT @AttendeeCount = COUNT(*)
    FROM Event.Attendees
   WHERE EventID = @EventID
     AND AccountID = @AccountID;
  
  IF @AttendeeCount > 0
    RETURN
  
  INSERT INTO Event.Attendees
  (
    EventID,
    AccountID
  )
  VALUES 
  (
    @EventID, 
    @AccountID
  );
  
  COMMIT TRANSACTION
END TRY
BEGIN CATCH
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
          @ERROR_STATE AS INT,
          @ERROR_NUMBER AS INT,
          @ERROR_LINE AS INT,
          @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT @ERROR_SEVERITY = ERROR_SEVERITY(),
         @ERROR_STATE = ERROR_STATE(),
         @ERROR_NUMBER = ERROR_NUMBER(),
         @ERROR_LINE = ERROR_LINE(),
         @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
            @ERROR_SEVERITY,
            @ERROR_STATE,
            @ERROR_NUMBER,
            @ERROR_LINE,
            @ERROR_MESSAGE);
END CATCH